package com.example.recordingpen_datacollection.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.recordingpen_datacollection.Utils.DateUtils.TimeJudgeUtils;
import com.example.recordingpen_datacollection.Utils.http.BDokHttpUtil;
import com.example.recordingpen_datacollection.Utils.http.OkHttpUtils;
import com.example.recordingpen_datacollection.entity.Businessdata;
import com.example.recordingpen_datacollection.entity.DosageStatistics;
import com.example.recordingpen_datacollection.entity.Logendtimeview;
import com.example.recordingpen_datacollection.entity.Vo.AISumUp;
import com.example.recordingpen_datacollection.entity.pojo.ChatCompletion;
import com.example.recordingpen_datacollection.entity.pojo.ChatCompletionSta;
import com.example.recordingpen_datacollection.mapper.DosageStatisticsMapper;
import com.example.recordingpen_datacollection.result.RLIST;
import com.example.recordingpen_datacollection.result.exceptionhandler.JWException;
import com.example.recordingpen_datacollection.service.AIService;
import com.example.recordingpen_datacollection.service.BaiduKeyService;
import com.example.recordingpen_datacollection.service.BusinessdataService;
import com.example.recordingpen_datacollection.service.DosageStatisticsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.example.recordingpen_datacollection.Utils.http.HttpUrl.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xg
 * @since 2023-11-29
 */
@Service
public class DosageStatisticsServiceImpl extends ServiceImpl<DosageStatisticsMapper, DosageStatistics> implements DosageStatisticsService {

    @Autowired
    private AIService aiService;
    @Autowired
    private BusinessdataService businessdataService;
    @Autowired
    private BaiduKeyService baiduKeyService;


    @Override
    public JSONObject getConference(Map<String, Object> map, String id) {
        String beginDate = (String) map.get("beginDate");
        String endDate = (String) map.get("endDate");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.ge("uaddtime",beginDate);
        wrapper.le("uaddtime",endDate);
        wrapper.eq("login_id",id);
        List<DosageStatistics> list = this.list(wrapper);
        String text = "会议时间段——"+beginDate+" -- "+endDate+"\n";
        if(list == null || list.size()<=0){
            text = "无会议总结";
        } else {
            for (DosageStatistics dosageStatistics : list) {
                String textName = dosageStatistics.getTextName();
                if(textName == null ||textName.isEmpty()){
                    continue;
                }
                String startMarker = "会议主题";
                String endMarker = "会议摘要";
                String textData = dosageStatistics.getFinalResult();
                int startIndex = textData.indexOf(startMarker) + startMarker.length();
                int endIndex = textData.indexOf(endMarker, startIndex); // 从startIndex开始查找endMarker

                if (startIndex != -1 && endIndex != -1) {
                    // 截取从startIndex（即“会议主题：”之后）到endIndex（不包括“会议摘要：”）之间的内容
                    String meetingTopicContent = textData.substring(startIndex-startMarker.length(), endIndex).trim();
                    text+=(textName+"\n"+meetingTopicContent+"\n");

                } else {
                    System.out.println("未找到完整的会议主题或会议摘要标记");

                }
            }
        }
        


        ChatCompletion chatCompletion = new ChatCompletion();
        chatCompletion.setCreated((System.currentTimeMillis()/1000));
        chatCompletion.setResult(text);
        chatCompletion.setObject("chat.completion");
        chatCompletion.setIs_truncated(false);

        return (JSONObject) JSONObject.toJSON(chatCompletion);
    }

    @Override
    public RLIST setDSMessage(AISumUp aiSumUp, Integer value) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("login_id",value);
        wrapper.eq("text_name",aiSumUp.getTextName());
        int count = this.count(wrapper);
        if(count>0){
            return RLIST.error().message("标题名重复");
        }

        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("login_id",value);
        Businessdata businessdataOne = businessdataService.getOne(wrapper2);
        boolean b = aiService.AISQLServer(aiSumUp, businessdataOne, false);

        return RLIST.ok();
    }
    private ExecutorService executorService = Executors.newFixedThreadPool(5);

    @Scheduled(fixedRate = 20000)
    @Override
    public void asynchronousProcessing(){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("state",0);
        Page<DosageStatistics> page = new Page<>(1, 10);
        this.page(page, wrapper);
        List<DosageStatistics> list = page.getRecords();
        if(list == null || list.size()<=0){
            return;
        }
        // 创建一个固定大小的线程池
        for (DosageStatistics dosageStatistics : list) {
            // 提交任务给线程池执行
            executorService.submit(new MyTask(dosageStatistics,this));
        }

        // 提交任务给线程池执行
//        executorService.submit(new MyTask());

        // 关闭线程池
//        executorService.shutdown();
    }

    @Override
    public JSONObject getConferenceV2(Map<String, Object> map, String id) {
        String beginDate = (String) map.get("beginDate");
        String endDate = (String) map.get("endDate");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.ge("uaddtime",beginDate);
        wrapper.le("uaddtime",endDate);
        wrapper.eq("login_id",id);
        List<DosageStatistics> list = this.list(wrapper);
        String text = "会议时间段——"+beginDate+" -- "+endDate+"\n";
        if(list == null || list.size()<=0){
            text = "无会议总结";
        } else {
            for (DosageStatistics dosageStatistics : list) {
                String textName = dosageStatistics.getTextName();
                if(textName == null ||textName.isEmpty()){
                    continue;
                }
                String startMarker = "会议主题";
                String endMarker = "会议摘要";
                String textData = dosageStatistics.getFinalResult();
                int startIndex = textData.indexOf(startMarker) + startMarker.length();
                int endIndex = textData.indexOf(endMarker, startIndex); // 从startIndex开始查找endMarker

                if (startIndex != -1 && endIndex != -1) {
                    // 截取从startIndex（即“会议主题：”之后）到endIndex（不包括“会议摘要：”）之间的内容
                    String meetingTopicContent = textData.substring(startIndex-startMarker.length(), endIndex).trim();
                    text+=(textName+"\n"+meetingTopicContent+"\n");

                } else {
                    System.out.println("未找到完整的会议主题或会议摘要标记");

                }
            }
        }



        ChatCompletionSta chatCompletion = new ChatCompletionSta();
        chatCompletion.setCreated((System.currentTimeMillis()/1000));
        chatCompletion.setResult(text);
        chatCompletion.setObject("chat.completion");
        chatCompletion.setIs_end(true);
        chatCompletion.setIs_truncated(false);
        chatCompletion.setSentence_id(0);
        return (JSONObject) JSONObject.toJSON(chatCompletion);
    }

    private class MyTask implements Runnable {
        private  DosageStatistics dosageStatistics;
        private DosageStatisticsService dosageStatisticsService;

        public MyTask(DosageStatistics dosageStatistics, DosageStatisticsService dosageStatisticsService) {
            this.dosageStatistics = dosageStatistics;
            this.dosageStatisticsService = dosageStatisticsService;
        }

        @Override
        public void run() {
            // 后台任务的逻辑代码
            System.out.println("Running background task...1");
            DosageStatistics dosageStatistics1 = new DosageStatistics();
            dosageStatistics1.setId(dosageStatistics.getId());
            dosageStatistics1.setState(1);
            boolean update = dosageStatisticsService.updateById(dosageStatistics1);
            if(!update){
                System.out.println("修改状态");
                return;
            }
            System.out.println("2");

            {
                System.out.println("获取key当前请求时间-------------》"+ TimeJudgeUtils.getNowDate());
                System.out.println(5);
                String access_token = null;

                access_token = baiduKeyService.BDtoken();
                if(access_token == null){
                    throw new JWException(500,"获取key失败");
                }
                String txtSumUp = null;
                try {
                    String urlData = BDurl8KData;
                    if(dosageStatistics.getText().length()>5000){//5000
                        urlData = BDurl128KData;
                        System.out.println("128K__");

                        JSONObject jsonObjectcon = new JSONObject();
                        jsonObjectcon.put("content",dosageStatistics.getText());
                        jsonObjectcon.put("baiduToken",access_token);
                        String doGet = OkHttpUtils.doPost2(NGINXURL,jsonObjectcon.toJSONString());
                        JSONObject jsonObject = JSON.parseObject(doGet);
                        JSONObject data = jsonObject.getJSONObject("data");
                        String error_code = data.getString("error_code");
                        if(error_code != null){
                            throw new JWException(500,data.toJSONString());
                        }
                        // 从JSONObject中提取值
                        String BDresult = data.getString("result");
                        txtSumUp = BDresult;
                    }
                    else {
                        //第二版本
                        String  getBDData = BDokHttpUtil.getBDData(urlData,access_token, "user", dosageStatistics.getText());
                        JSONObject jsonObject = JSON.parseObject(getBDData);
                        String error_code = jsonObject.getString("error_code");
                        if(error_code != null){
                            throw new JWException(500,getBDData);
                        }
                        // 从JSONObject中提取值
                        String BDresult = jsonObject.getString("result");
                        txtSumUp = BDresult;
                    }
                    //第一版本
//               String  getBDData = BDokHttpUtil.getBDData(urlData,access_token, "user", aiSumUp.getContent());
//                JSONObject jsonObject = JSON.parseObject(getBDData);
//                String error_code = jsonObject.getString("error_code");
//                if(error_code != null){
//                    throw new JWException(500,getBDData);
//                }
//                // 从JSONObject中提取值
//                String BDresult = jsonObject.getString("result");
//                txtSumUp = BDresult;

                } catch (IOException e) {
                    throw new JWException(500,"访问DB异常");
                }

                dosageStatistics1.setId(dosageStatistics.getId());
                dosageStatistics1.setState(2);
                dosageStatistics1.setFinalResult(txtSumUp);
                boolean update2 = dosageStatisticsService.updateById(dosageStatistics1);
                if(!update2){
                    System.out.println("修改状态");
                    return;
                }
            }
        }

    }
}
